import { useKeyPress } from 'ahooks';
import { useDispatch } from 'react-redux';
import { ActionCreators } from 'redux-undo';
import {
  removeSelectedComponent,
  copySelectedComponent,
  pasteCopiedComponent,
  selectPrevComponent,
  selectNextComponent,
} from '../store/ComponentsReducer';

const isActiveElementValid = () => {
  const activeElement = document.activeElement;
  if (activeElement === document.body) return true;
  if (activeElement?.matches('div[role="button"]')) return true;
  return false;
};

const useBindCanvasKeyPress = () => {
  const dispatch = useDispatch();
  useKeyPress(['backspace', 'delete'], () => {
    if (!isActiveElementValid()) return;
    dispatch(removeSelectedComponent());
  });
  useKeyPress(['ctrl.c', 'meta.c'], () => {
    if (!isActiveElementValid()) return;
    dispatch(copySelectedComponent());
  });
  useKeyPress(['ctrl.v', 'meta.v'], () => {
    if (!isActiveElementValid()) return;
    dispatch(pasteCopiedComponent());
  });
  useKeyPress(['uparrow'], () => {
    if (!isActiveElementValid()) return;
    dispatch(selectPrevComponent());
  });
  useKeyPress(['downarrow'], () => {
    if (!isActiveElementValid()) return;
    dispatch(selectNextComponent());
  });
  useKeyPress(
    ['ctrl.z', 'meta.z'],
    () => {
      if (!isActiveElementValid()) return;
      dispatch(ActionCreators.undo());
    },
    { exactMatch: true }
  );
  useKeyPress(
    ['ctrl.y', 'meta.y'],
    () => {
      if (!isActiveElementValid()) return;
      dispatch(ActionCreators.redo());
    },
    { exactMatch: true }
  );
};

export default useBindCanvasKeyPress;
